package com.wanli.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanli.common.Result;
import com.wanli.domain.entity.Business;
import com.wanli.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wanli.common.BaseController;

import java.time.LocalDateTime;
import java.util.Arrays;

@RestController
@RequestMapping("/business")
public class BusinessController extends BaseController {
    @Autowired
    private BusinessService businessService;

    @PostMapping("/update")
    public Result update(@RequestBody Business business) {
        business.setUpdated(LocalDateTime.now());
        businessService.updateById(business);
        return Result.success("商家数据更新成功");
    }

    @GetMapping("/getById/{businessId}")
    public Result getById(@PathVariable Long businessId) {
        Business business = businessService.getById(businessId);
        return Result.success(business);
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody String[] businessIds) {
        // Arrays.asList(数组) 将数组转化为 List集合
        businessService.removeByIds(Arrays.asList(businessIds));
        return Result.success("商家信息删除成功");
    }


    @PostMapping("/save")
    public Result save(@RequestBody Business business) {
        if (business.getBusinessImg() == null || business.getBusinessImg().length() < 0) {
            // 如果上传图片为空，给默认的
            business.setBusinessImg("https://alextachalova.com/wp-content/themes/wp-wellow/assets/images/no-image.jpg");
        }
        business.setCreated(LocalDateTime.now());
        business.setUpdated(LocalDateTime.now());
        business.setDelTag(1); // 逻辑删除 1表示没有删除0删除
        businessService.save(business);
        return Result.success("商家信息保存成功");
    }

    @GetMapping("/list")
    public Result list(String businessName) {
        Page<Business> businessList = businessService.page(getPage(),
                new QueryWrapper<Business>
                        ().like(StrUtil.isNotBlank(businessName), "business_name", businessName));
        return Result.success(businessList);
    }

    /**
     * 统计入驻店铺数量
     * @return
     */
    @GetMapping("/count")
    public Result getBusinessCount() {
        return Result.success(businessService.count());
    }
}